package org.oep.jmingle;

import java.io.IOException;
import org.oep.widgets.ChoiceWidget;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;


/**
 * This screen is the "main menu." Here, the player can
 * choose which part of the game to go to.
 * @author pmkilgo
 *
 */
public class LandingScreen extends Canvas {
	private Image banner;
	private ChoiceWidget menu;
	private EventPipe listener;
	
	private final int choiceField;
	private final int choiceTutorial;
	private final int choiceQuit;
	
	/**
	 * This constructor takes an EventPipe. This should be the MIDlet, in the most
	 * normal case. It will send events (expecting class JMingle) telling it to
	 * direct the user to a new screen.
	 * @param listener
	 */
	LandingScreen(EventPipe listener) {
		menu = new ChoiceWidget(ChoiceWidget.TYPE_LIST);
		menu.setPosition(getWidth() / 2, getHeight() / 2);
		
		menu.setDefaultFont(JMingle.DEFAULT_FONT);
		menu.setSelectedFont(JMingle.BOLD_FONT);
		
		menu.setActive(true);
		
		choiceField = menu.addChoice("The Field");
		choiceTutorial = menu.addChoice("Tutorial");
		choiceQuit = menu.addChoice("Quit");
		try {
			banner = Image.createImage("/res/graphics/jmingle-banner.png");
		}
		catch(IOException e) {
			
		}
		
		this.listener = listener;
	}
	
	/**
	 * This function merely resets to the default choice in the menu.
	 */
	public void toInitialState() {
		menu.setChoice(choiceField);
	}
	
	/**
	 * keyPressed() is used to cycle through the ChoiceMenu and to select a choice.
	 */
	public void keyPressed(int keyCode) {
		keyCode = this.getGameAction(keyCode);
		
		switch(keyCode) {
		case Canvas.DOWN: menu.nextChoice(); repaint(); break;
		case Canvas.UP: menu.previousChoice(); repaint(); break;
		case Canvas.FIRE: selectionMade(); break;
		}
	}
	
	/**
	 * This method paints everything, of course. No really. That's all it does.
	 * Who'd a thunk it?
	 */
	public void paint(Graphics g) {
		g.setFont(JMingle.DEFAULT_FONT);
		g.setColor(0xFFFFFF);
		g.fillRect(0, 0, getWidth(), getHeight());
		g.drawImage(banner, getWidth() / 2, getHeight() / 2, Graphics.BOTTOM | Graphics.HCENTER);
		menu.paint(g);
		g.setColor(0);
		g.drawString(JMingle.VERSION, 3, getHeight(), Graphics.BOTTOM | Graphics.LEFT);
	}

	/**
	 * Handle the case when the user has made a choice.
	 */
	private void selectionMade() {
		int choice = menu.getChoiceIndex();
		if(choice == choiceTutorial) listener.eventReceived(JMingle.SHOW_TUTORIAL);
		else if(choice == choiceField) listener.eventReceived(JMingle.SHOW_FIELD);
		else if(choice == choiceQuit) listener.eventReceived(JMingle.QUIT_APP);
	}
}

